package com.sin.j2me.util;

public class Stack {
	private Object[] container = null;
	public static int DEFAULT_CAPACITY = 10;
	private int top = -1;
	public Stack() {
		this(DEFAULT_CAPACITY);
	}
	
	public Stack(int capacity){
		this.container = new Object[capacity];
		this.top = 0;
	}
	
	public int push(Object obj) {
		if(full()){
			newCapacity();
		}
		this.container[this.top] = obj;
		++this.top;
		return this.top;
	}
	
	public Object pop() {
		if(empty()){
			throw new IndexOutOfBoundsException("Stack Empty!");
		}
		else{
			--this.top;
			Object obj = this.container[this.top];
			this.container[this.top] = null;
			return obj;
		}
	}
	
	public Object top() {
		if(empty()){
			throw new IndexOutOfBoundsException("Stack Empty!");
		}
		else{
			return this.container[this.top - 1];
		}
	}
	
	public Object get(int ix){
		return container[ix];
	}
	
	public boolean empty() {
		return this.top<=0;
	}
	
	public boolean full() {
		return this.container.length<=this.top;
	}
	
	private int newCapacity(){
		int newlen = this.container.length * 2;
		Object[] srcs = this.container;
		this.container = new Object[newlen];
		System.arraycopy(srcs, 0, container, 0, srcs.length);
		return newlen;
	}
	
	public int size() {
		return this.top;
	}
}
